import axios from 'axios';
import { ethers } from 'ethers';

/**
 * XLayer LaunchPad end-to-end test script
 * Steps:
 * 1. Create launch (POST /api/xlayer/tokens)
 * 2. Buy tokens (POST /api/xlayer/tokens/:launchId/buy)
 * 3. Sell a portion (POST /api/xlayer/tokens/:launchId/sell)
 *
 * Usage (from backend directory):
 *   TEST_PK=0x<privateKey> npx ts-node scripts/xlayer-flow-test.ts
 *   (or set BACKEND_URL if not running on default http://localhost:7172)
 */

interface CreateResp {
  id: string;
  launchId: number;
  tokenAddress: string;
  creator: string;
  txHash: string;
}

const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:7172';
const PRIVATE_KEY = process.env.TEST_PK || process.env.PRIVATE_KEY || 'REPLACE_ME';
const TARGET_AMOUNT_ETH = '5';
const BUY_ETH = '0.01';

async function main() {
  if (!PRIVATE_KEY || PRIVATE_KEY === 'REPLACE_ME') {
    console.error('Missing TEST_PK env (private key)');
    process.exit(1);
  }
  const wallet = new ethers.Wallet(PRIVATE_KEY);
  console.log('Using wallet:', wallet.address);

  // 1. Create launch
  console.log('\n== Create Launch ==');
  const createBody = {
    name: 'TestX',
    symbol: 'TSTX',
    description: 'demo launch',
    targetAmount: Number(TARGET_AMOUNT_ETH),
    creatorPrivateKey: PRIVATE_KEY,
    website: '',
    telegram: '',
    twitter: ''
  };
  const createRes = await axios.post(`${BACKEND_URL}/api/xlayer/tokens`, createBody, { timeout: 120000 });
  const created: any = createRes.data;
  console.log('Create response:', created);
  const launchId = created.launchId || Number((created.id || '').split('_')[1]);
  if (launchId === undefined) throw new Error('Cannot determine launchId');
  console.log('LaunchId:', launchId);

  // 2. Buy tokens
  console.log('\n== Buy Tokens ==');
  const buyBody = {
    launchId,
    ethAmount: Number(BUY_ETH),
    buyerAddress: wallet.address,
    buyerPrivateKey: PRIVATE_KEY
  };
  const buyRes = await axios.post(`${BACKEND_URL}/api/xlayer/tokens/${launchId}/buy`, buyBody, { timeout: 120000 });
  const buyData: any = buyRes.data;
  console.log('Buy response:', buyData);
  const tokensReceivedStr = buyData.tokensReceived || '0';
  const tokensReceived = Number(tokensReceivedStr);

  // Decide sell amount (min 1, else 50% if small)
  let sellAmount = Math.floor(tokensReceived * 0.1); // 10%
  if (sellAmount < 1) sellAmount = Math.max(1, Math.floor(tokensReceived / 2));
  console.log(`Planned sell amount: ${sellAmount} (from tokensReceived=${tokensReceivedStr})`);

  // 3. Sell tokens
  console.log('\n== Sell Tokens ==');
  const sellBody = {
    launchId,
    tokenAmount: sellAmount,
    sellerAddress: wallet.address,
    sellerPrivateKey: PRIVATE_KEY
  };
  const sellRes = await axios.post(`${BACKEND_URL}/api/xlayer/tokens/${launchId}/sell`, sellBody, { timeout: 120000 });
  const sellData: any = sellRes.data;
  console.log('Sell response:', sellData);

  console.log('\nFlow complete. Summary:');
  console.log({
    launchId,
    createTx: created.txHash,
    buyTx: buyData.txHash,
    sellTx: sellData.txHash,
    tokensReceived: tokensReceivedStr,
    sold: sellAmount,
    newPriceAfterBuy: buyData.newPrice,
    newPriceAfterSell: sellData.newPrice,
    ethReceivedOnSell: sellData.ethReceived
  });
}

main().catch(e => {
  console.error('Flow failed:', e);
  process.exit(1);
});
